package com.esheeper.CAS.Service;


import com.esheeper.CAS.Pojo.User;
import com.esheeper.CAS.Util.CryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * UserService
 *
 * @author Wenyang Su
 * @version 1.0.0
 * @description 关于用户的服务接口
 * @date 2023-05-16
 */

@Service
public class UserService {

    @Autowired
    CryptUtil cryptUtil;
    @Autowired
    MongoTemplate mongoTemplate;

    public User findUserByUsernameAndPassword(User user) throws NoSuchAlgorithmException {
        user.setPassword(cryptUtil.FormatPassword(user.getPassword()));
        Query query = Query.query(Criteria.where("username").is(user.getUsername()).and("password").is(user.getPassword()));
        List<User> userList = mongoTemplate.find(query,User.class);
;       if(userList.size() == 0){
            return null;
        }else{
            return userList.get(0);
        }
    }

    public User insertUser(User user) throws NoSuchAlgorithmException {
        user.setPassword(cryptUtil.FormatPassword(user.getPassword()));
        mongoTemplate.save(user);
        return user;
    }

    public User updateUser(User user) throws NoSuchAlgorithmException {
        user.setPassword(cryptUtil.FormatPassword(user.getPassword()));
        Query query = Query.query(Criteria.where("username").is(user.getUsername()));
        Update update = Update.update("password",user.getPassword());
        mongoTemplate.updateFirst(query,update,User.class);
        return user;
    }

}
